package com.example.neteasecloudmusic.ui;

import static com.example.neteasecloudmusic.enumclass.PlayModeEnum.*;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.Time;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.request.RequestOptions;
import com.example.neteasecloudmusic.R;
import com.example.neteasecloudmusic.bean.SongDetailInfo;
import com.example.neteasecloudmusic.bean.playListBean.Tracks;
import com.example.neteasecloudmusic.enumclass.PlayModeEnum;
import com.example.neteasecloudmusic.greenDaoGen.SongDetailController;
import com.example.neteasecloudmusic.help.DestroyActivityUtil;
import com.example.neteasecloudmusic.help.TimeUtil;
import com.example.neteasecloudmusic.ui.base.BaseActivity;
import com.example.neteasecloudmusic.ui.player.MusicRelateOptions;
import com.example.neteasecloudmusic.ui.song_list_detail.MyDialogFragment;
import com.example.neteasecloudmusic.view.PlayMusicView;

import java.io.IOException;
import java.util.List;

import jp.wasabeef.glide.transformations.BitmapTransformation;
import jp.wasabeef.glide.transformations.BlurTransformation;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;

public class PlayMusicActivity extends BaseActivity {
    private static MediaPlayer mediaPlayer;
    private Boolean isPause = false;
    private static final String PATH = "url";
//    private static List<Tracks> tracks;
    private List<SongDetailInfo> songDetailInfos;
    private static Integer position, prePosition;
    private static SeekBar seekBar;
    private static Time time;
    private  final int MSG = 0x001;
    private PlayModeEnum MODE = LOOP;
    private static MusicRelateOptions musicRelateOptions;
    private int step = 1;
    private ImageView btn_play, btn_next, btn_back, btn_play_mode, play_bg, btn_play_menu;
    private TextView play_song, play_singer, music_curr_time, music_total_time;
    private String img, song, singer;
    private PlayMusicView mPlayMusicView;
    private TimeUtil timeUtil;
    private MyDialogFragment dialogFragment;
    private SongDetailController mSongDetailController;

    @Override
    protected void initViews() {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        DestroyActivityUtil.addDestroyActivityToMap(PlayMusicActivity.this, "PlayMusicActivity");
        Intent intent = getIntent();
        mediaPlayer = mediaPlayer == null ? new MediaPlayer() : mediaPlayer;
        position = intent.getIntExtra("position", 0);
        mSongDetailController = SongDetailController.getInstance(getApplicationContext());
        songDetailInfos = mSongDetailController.searchAll();
        String id = songDetailInfos.get(position).getUrl();

        musicRelateOptions = musicRelateOptions == null ? new MusicRelateOptions(mediaPlayer, songDetailInfos, PATH) : musicRelateOptions;
        try {
            if (prePosition == null || !prePosition.equals(position)) {
                prePosition = position;
                musicRelateOptions.play(id);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        findAllViewById();
        seekBar.setProgress(mediaPlayer.getCurrentPosition());
        playCover(position);
        mPlayMusicView.setMusicIcon(songDetailInfos.get(position).getPic());
        mPlayMusicView.playMusic();

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                handler.sendEmptyMessage(MSG);
            }
        });
        thread.start();

        timeUtil = new TimeUtil();

        btn_play_mode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playModeChange((ImageView) v);
            }
        });
        btn_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playOrPauseMusic((ImageView) v);
            }
        });
        btn_next.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                nextMusic();
            }
        });
        btn_back.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                preMusic();
            }
        });

        btn_play_menu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // show playList Dialog Fragment
                dialogFragment = new MyDialogFragment(songDetailInfos, position, songDetailInfos.get(position));
                dialogFragment.show(getSupportFragmentManager(), "dialog");
            }
        });

        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                    if (MODE == ONE) {
                        if (isPause) {
                            btn_play.setImageDrawable(getResources().getDrawable(R.drawable.ic_play, null));
                        }
                        step = 0;
                        position = musicRelateOptions
                                .PreMusic((position - step) < 0 ? (position - step + songDetailInfos.size()) : (position - step));
                        playCover(position);
                        mPlayMusicView.setMusicIcon(songDetailInfos.get(position).getPic());
                        mPlayMusicView.playMusic();
                    } else {
                        nextMusic();
                    }
            }
        });
    }

    /**
     * 定义的View
     */
    private void findAllViewById() {
        music_curr_time = findViewById(R.id.music_curr_time);
        music_total_time = findViewById(R.id.music_total_time);
        seekBar = (SeekBar) findViewById(R.id.seekBar);
        seekBar.setMax(mediaPlayer.getDuration());
        btn_play = findViewById(R.id.btn_play);
        btn_next = findViewById(R.id.btn_next);
        btn_back = findViewById(R.id.btn_back);
        btn_play_mode = findViewById(R.id.btn_play_mode);
        btn_play_menu = findViewById(R.id.btn_play_menu);
        play_song =  findViewById(R.id.play_song);
        play_singer =  findViewById(R.id.play_singer);
        play_bg = findViewById(R.id.play_bg);
        mPlayMusicView = findViewById(R.id.play_music_view);
    }

    /**
     * 上一首歌
     */
    private void preMusic() {
        if (isPause) {
            btn_play.setImageDrawable(getResources().getDrawable(R.drawable.ic_play, null));
        }
        step = stepChoice();
        position = musicRelateOptions
                .PreMusic((position - step) < 0 ? (position - step + songDetailInfos.size()) : (position - step));
        playCover(position);
        mPlayMusicView.setMusicIcon(songDetailInfos.get(position).getPic());
        mPlayMusicView.playMusic();
    }

    /**
     * 下一首歌
     */
    private void nextMusic() {
        if (isPause) {
            btn_play.setImageDrawable(getResources().getDrawable(R.drawable.ic_play, null));
        }
        step = stepChoice();
        position = musicRelateOptions
                .NextMusic((position + step) >= songDetailInfos.size() ?
                        (position + step) % songDetailInfos.size() : (position + step));
        playCover(position);
        mPlayMusicView.setMusicIcon(songDetailInfos.get(position).getPic());
        mPlayMusicView.playMusic();
    }

    /**
     * 播放或暂停
     * @param v
     */
    private void playOrPauseMusic(ImageView v) {
        if(mediaPlayer.isPlaying() && !isPause){
            mediaPlayer.pause();
            mPlayMusicView.stopMusic();
            isPause = true;
            v.setImageDrawable(getResources().getDrawable(R.drawable.ic_pause,null));
        }else{
            mediaPlayer.start();
            mPlayMusicView.playMusic();
            isPause = false;
            v.setImageDrawable(getResources().getDrawable(R.drawable.ic_start,null));
        }
    }

    /**
     * 切换三种播放模式
     * @param v
     */
    private void playModeChange(ImageView v) {
        switch (MODE) {
            case RANDOM: {
                MODE = LOOP;
                v.setImageDrawable(getResources().getDrawable(R.drawable.ic_playmode_loop,null));
                Toast.makeText(getApplicationContext(), "循环播放", Toast.LENGTH_SHORT).show();
            } break;
            case LOOP: {
                MODE = ONE;
                v.setImageDrawable(getResources().getDrawable(R.drawable.ic_playmode_one,null));
                Toast.makeText(getApplicationContext(), "单曲循环", Toast.LENGTH_SHORT).show();
            } break;
            case ONE: {
                MODE = RANDOM;
                v.setImageDrawable(getResources().getDrawable(R.drawable.ic_playmode_random,null));
                Toast.makeText(getApplicationContext(), "随机播放", Toast.LENGTH_SHORT).show();
            } break;
        }
    }

    /**
     * 切换歌曲 同时更改封面和歌曲信息
     * @param position
     */
    private void playCover(int position) {
        song = songDetailInfos.get(position).getSongName();
        singer = songDetailInfos.get(position).getSingerName();
        img = songDetailInfos.get(position).getPic();
        play_song.setText(this.song);
        play_singer.setText(this.singer);

        Glide.with(this)
                .load(this.img)
                .apply(RequestOptions.bitmapTransform(new BlurTransformation(25, 50)))
                .into(play_bg);
    }

    /**
     * 定义歌曲切换的步长
     * @return
     */
    private int stepChoice() {
        if (MODE == RANDOM) {
            step = (int) (Math.random() * songDetailInfos.size()) + 1;
        } else step = 1;
        return step;
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler(){
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if(msg.what == MSG){
                seekBar.setProgress(mediaPlayer.getCurrentPosition());
                music_curr_time.setText(timeUtil.stringForTime(mediaPlayer.getCurrentPosition()));
                music_total_time.setText(timeUtil.stringForTime(mediaPlayer.getDuration()));
                seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                    @Override
                    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                        if(fromUser){
                            mediaPlayer.seekTo(seekBar.getProgress());
                        }
                    }
                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {
                    }
                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {
                    }
                });
            }
            handler.sendEmptyMessageDelayed(MSG,1000);
        }
    };


    @Override
    protected int getLayoutId() {
        return R.layout.activity_play_music;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public void onBackClick(View view) {
        onBackPressed();
    }
}
